package com.pulsehematometry.serial.setup;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.TooManyListenersException;

import org.apache.log4j.Logger;

import com.lwisniewski.pg.pulsehematometry.serial.main.SerialPortListener;


import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;

public class SerialPortReaderSetup {

	private final static Logger LOGGER = Logger
			.getLogger(SerialPortReaderSetup.class);

	private static SerialPortReaderSetup serialPortReaderSetup;
	private static CommPortIdentifier usedPort;
	private static SerialPort serialPort;

	private static CommPortIdentifier portId;
	private static Enumeration<CommPortIdentifier> portList;
	
	public static SerialPortReaderSetup getInstance() {
		if (serialPortReaderSetup == null) {
			synchronized (SerialPortReaderSetup.class) {
				if (serialPortReaderSetup == null) {
					serialPortReaderSetup = new SerialPortReaderSetup();
				}
			}
		}
		return serialPortReaderSetup;
	}
	
	public void openPort(CommPortIdentifier usedPort) {
		try {
			serialPort = (SerialPort) portId.open("SimpleReadApp", 2000);
			serialPort.notifyOnDataAvailable(true);
			serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8,
					SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);

		} catch (Exception e) {
			LOGGER.error("Exception occured when opening serial port. "
					+ e.getMessage());
		}
	}

	public void closePort(CommPortIdentifier usedPort) {
		serialPort.close();
	}

	public CommPortIdentifier getUsedCommPortIdentifier() {
		return usedPort;
	}

	public List<CommPortIdentifier> getAvailableSerialPortList() {

		List<CommPortIdentifier> commPortList = new ArrayList<CommPortIdentifier>();
		portList = CommPortIdentifier.getPortIdentifiers();

		while (portList.hasMoreElements()) {
			portId = (CommPortIdentifier) portList.nextElement();
			if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
				commPortList.add(portId);
			}
		}
		return commPortList;
	}
	
	public InputStream getRs232InputStream() throws IOException {
		return serialPort.getInputStream();
	}
	
}
